<template>
  <el-card style="max-width: 600px; margin: 50px auto;">
    <template #header>
      <div style="text-align: center;">
        <h2>修改角色信息</h2>
      </div>
    </template>
    
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="角色ID" prop="RoleId">
        <el-input v-model="formData.RoleId" disabled />
      </el-form-item>
      
      <el-form-item label="角色名" prop="RoleName">
        <el-input v-model="formData.RoleName" placeholder="请输入角色名" />
      </el-form-item>
      
      <el-form-item label="权限" prop="PermissionId">
        <el-select-v2
          v-model="formData.PermissionId"
          placeholder="请选择权限"
          :options="permissionOptions"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存修改</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import axios from 'axios';

interface Role {
  RoleId: number;
  RoleName: string;
  PermissionId?: number;
}

const route = useRoute();
const router = useRouter();
const formRef = ref<FormInstance>();

const formData = ref<Role>({
  RoleId: 0,
  RoleName: '',
  PermissionId: 0
});

const permissionOptions = ref<any[]>([]);

const rules = ref<FormRules>({
  RoleName: [
    { required: true, message: '请输入角色名', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名长度在2到20个字符', trigger: 'blur' }
  ],
  PermissionId: [
    { required: true, trigger: 'blur', validator(rule, value, callback) {
      if (!value || value === 0) {
        callback(new Error('请选择权限'));
      } else {
        callback();
      }
    } }
  ]
});

// 获取权限列表
const getPermissionList = () => {
  axios({
    url: "http://localhost:5028/api/Management/GetPermissionItem",
    method: "get"
  })
  .then(res => {
    console.log('权限列表:', res);
    if (res.data.Code === 200) {
      permissionOptions.value = res.data.Result.map((item: any) => ({
        value: item.value,
        label: item.label
      }));
      // 添加请选择选项
      permissionOptions.value.unshift({ value: 0, label: '请选择' });
    }
  })
  .catch(error => {
    console.error('获取权限列表失败:', error);
  });
};

// 获取角色详情
const getRoleDetail = () => {
  axios({
    url: "http://localhost:5028/api/Management/GetRoleDetail",
    method: "get",
    params: { RoleId: route.params.id }
  })
  .then(res => {
    console.log('角色详情:', res);
    if (res.data.Code === 200) {
      formData.value = res.data.Result;
      // 确保PermissionId有默认值
      if (!formData.value.PermissionId) {
        formData.value.PermissionId = 0;
      }
    }
  })
  .catch(error => {
    console.error('获取角色详情失败:', error);
  });
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    const response = await axios.put('http://localhost:5117/api/Operate/UpdateRole', formData.value);
    console.log(response)
    if (response.data.Code === 400) {
      ElMessage.success('修改成功');
      router.push('/ShowRole');
    } else {
      ElMessage.error(response.data.Message || '修改失败');
    }
  } catch (error: any) {
    if (error.response?.data?.Message) {
      ElMessage.error(error.response.data.Message);
    } else {
      ElMessage.error('修改失败');
    }
  }
};

// 返回
const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  getPermissionList();
  getRoleDetail();
});
</script>

<style scoped>
.el-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 20px;
}
</style>